package org.jeecg.modules.custom.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.minio.messages.Item;
import io.minio.messages.Prefix;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.logging.log4j.util.PerformanceSensitive;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.common.CommonUtil;
import org.jeecg.modules.providers.entity.MtServiceProviders;
import org.jeecg.modules.providers.service.IMtServiceProvidersService;
import org.jeecg.modules.station.entity.MtServiceStation;
import org.jeecg.modules.station.service.IMtServiceStationService;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.util.PositionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.*;

import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.custom.entity.MtCustomEquip;
import org.jeecg.modules.custom.entity.MtCustorm;
import org.jeecg.modules.custom.service.IMtCustormService;
import org.jeecg.modules.custom.service.IMtCustomEquipService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * @Description: 客户表
 * @Author: jeecg-boot
 * @Date: 2022-08-19
 * @Version: V1.0
 */
@Api(tags = "客户表")
@RestController
@RequestMapping("/custom/mtCustorm")
@Slf4j
public class MtCustormController extends JeecgController<MtCustorm, IMtCustormService> {

    @Autowired
    private IMtCustormService mtCustormService;
    @Autowired
    private IMtCustomEquipService mtCustomEquipService;
    @Autowired
    private IMtServiceProvidersService mtServiceProvidersService;
    @Autowired
    private IMtServiceStationService mtServiceStationService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysUserService sysUserService;


    /*---------------------------------主表处理-begin-------------------------------------*/

    /**
     * 分页列表查询
     *
     * @param mtCustorm
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "客户表-分页列表查询")
    @ApiOperation(value = "客户表-分页列表查询", notes = "客户表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<MtCustorm>> queryPageList(MtCustorm mtCustorm,
                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                  HttpServletRequest req) {
        QueryWrapper<MtCustorm> queryWrapper = QueryGenerator.initQueryWrapper(mtCustorm, req.getParameterMap());
        Page<MtCustorm> page = new Page<MtCustorm>(pageNo, pageSize);
        IPage<MtCustorm> pageList = mtCustormService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 根据当前登录服务商分页列表查询
     *
     * @param mtCustorm
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "客户表-根据当前登录服务商分页列表查询")
    @ApiOperation(value = "客户表-根据当前登录服务商分页列表查询", notes = "客户表-根据当前登录服务商分页列表查询")
    @GetMapping(value = "/listByLoginUser")
    public Result<IPage<MtCustorm>> listByLoginUser(MtCustorm mtCustorm,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();//2.0版本获取当前登录用户
        QueryWrapper<MtCustorm> queryWrapper = QueryGenerator.initQueryWrapper(mtCustorm, req.getParameterMap());
        Page<MtCustorm> page = new Page<MtCustorm>(pageNo, pageSize);
        // 登录用户为平台管理员
        if (loginUser.getUserType() == 0) {
            IPage<MtCustorm> pageList = mtCustormService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
        // 登陆用户为服务商
        else if (loginUser.getUserType() == 1) {
            MtServiceProviders mtServiceProviders = mtServiceProvidersService.getById(loginUser.getLinkId());
            if (Objects.isNull(mtServiceProviders)) {
                return Result.error("服务商信息不存在!");
            }
            queryWrapper.eq("provider_id", mtServiceProviders.getId());
        }
        // 登陆用户为服务站
        else if (loginUser.getUserType() == 2) {
            MtServiceStation mtServiceStation = mtServiceStationService.getById(loginUser.getLinkId());
            if (Objects.isNull(mtServiceStation)) {
                return Result.error("服务站信息不存在!");
            }
            queryWrapper.eq("station_id", mtServiceStation.getId());
        }
        // 登陆用户为其他
        else {
            return Result.error("该登录用户不是服务商或服务站");
        }
        IPage<MtCustorm> pageList = mtCustormService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param mtCustorm
     * @return
     */
    @AutoLog(value = "客户表-添加")
    @ApiOperation(value = "客户表-添加", notes = "客户表-添加")
    @PostMapping(value = "/add")
    @RequiresPermissions("custom:add")
    public Result<String> add(@RequestBody MtCustorm mtCustorm) {
        // 生成编号
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();//2.0版本获取当前登录用户
        SysUser user = sysUserService.getById(loginUser.getId());
        // 角色为服务商
        if (user.getUserType() == 1) {
            MtServiceProviders mtServiceProviders = mtServiceProvidersService.getOne(new LambdaQueryWrapper<MtServiceProviders>()
                    .eq(MtServiceProviders::getUserId, user.getUsername()));
            // 设置服务商
            mtCustorm.setProviderId(mtServiceProviders.getId());
            mtCustorm.setSysOrgCode(mtServiceProviders.getSysOrgCode());
        }
        mtCustormService.saveUserAndRole(mtCustorm);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mtCustorm
     * @return
     */
    @AutoLog(value = "客户表-编辑")
    @ApiOperation(value = "客户表-编辑", notes = "客户表-编辑")
    @RequiresPermissions("custom:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody MtCustorm mtCustorm) {
        mtCustormService.updateById(mtCustorm);
        return Result.OK("编辑成功!");
    }

    /**
     * 地图标注
     *
     * @param mtCustorm
     * @return
     */
    @AutoLog(value = "客户表-地图标注")
    @ApiOperation(value = "客户表-地图标注", notes = "客户表-地图标注")
    @RequiresPermissions("custom:coordinate")
    @RequestMapping(value = "/coordinate", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> coordinate(@RequestBody MtCustorm mtCustorm) {
        if (StrUtil.isBlank(mtCustorm.getProviderId())) {
            Result.error("未设置服务商!");
        }
        // 获取服务商下属工作站列表
        List<MtServiceStation> stations = mtServiceStationService.list(new LambdaQueryWrapper<MtServiceStation>()
                .eq(MtServiceStation::getProviderId, mtCustorm.getProviderId()));
        if (stations.isEmpty()) {
            return Result.error("服务商无下属服务站");
        }
        //longitudeA 第一个点的经度
        //latitudeA  第一个点的纬度
        String[] croods = StringUtils.split(mtCustorm.getCrood(), ",");
        double longitudeA = Double.parseDouble(croods[0]);
        double latitudeA = Double.parseDouble(croods[1]);
        // 计算工作站与客户的距离
        stations.forEach(station -> {
            if (StrUtil.isBlank(station.getCoordinate())) {
                return;
            }
            //longitudeB 第二个点的经度
            //latitudeB  第二个点的纬度
            String[] croodsB = StringUtils.split(station.getCoordinate(), ",");
            double longitudeB = Double.parseDouble(croodsB[0]);
            double latitudeB = Double.parseDouble(croodsB[1]);
            double distance = PositionUtil.getDistance(longitudeA, latitudeA, longitudeB, latitudeB);
            station.setDistance(distance);
        });
        // 筛选工作站与客户的最短距离
        MtServiceStation nearStation = stations.stream()
                .filter(station -> station.getDistance() != null)
                .min(Comparator.comparing(MtServiceStation::getDistance)).orElse(null);
        if (Objects.isNull(nearStation)) {
            return Result.error("无合适服务站");
        }
        // 绑定服务站
        mtCustorm.setStationId(nearStation.getId());
        // 绑定orgCode
        mtCustorm.setSysOrgCode(nearStation.getSysOrgCode());
        mtCustormService.updateById(mtCustorm);
        return Result.OK("标注成功!");
    }

    /**
     * 设置服务商
     *
     * @param mtCustorm
     * @return
     */
    @AutoLog(value = "客户表-设置服务商")
    @ApiOperation(value = "客户表-设置服务商", notes = "客户表-设置服务商")
    @RequiresPermissions("custom:allot")
    @RequestMapping(value = "/allot", method = {RequestMethod.PUT, RequestMethod.POST})
    @Transactional(rollbackFor = Exception.class)
    public Result<String> allot(@RequestBody MtCustorm mtCustorm) {
        List<MtCustomEquip> list = mtCustomEquipService.selectByMainId(mtCustorm.getId());
        if (list != null) {
            if (list.size() > 0) {
                for (MtCustomEquip mtCustomEquip : list) {
                    if (mtCustomEquip != null) {
                        mtCustomEquip.setProviderId(mtCustorm.getProviderId());
                        mtCustomEquip.setStationId("");//清除已设置的服务站
                        mtCustomEquipService.updateById(mtCustomEquip);
                    }
                }
            }
        }
        mtCustorm.setStationId("");
        mtCustormService.updateById(mtCustorm);
        return Result.OK("服务商设置成功!");
    }

    /**
     * 设置服务站
     *
     * @param mtCustorm
     * @return
     */
    @AutoLog(value = "客户表-设置服务站")
    @ApiOperation(value = "客户表-设置服务站", notes = "客户表-设置服务站")
    @RequiresPermissions("custom:allotStation")
    @RequestMapping(value = "/allotStation", method = {RequestMethod.PUT, RequestMethod.POST})
    @Transactional(rollbackFor = Exception.class)
    public Result<String> allotStation(@RequestBody MtCustorm mtCustorm) {
        List<MtCustomEquip> list = mtCustomEquipService.selectByMainId(mtCustorm.getId());
        if (list != null) {
            if (list.size() > 0) {
                for (MtCustomEquip mtCustomEquip : list) {
                    if (mtCustomEquip != null) {
                        mtCustomEquip.setStationId(mtCustorm.getStationId());//清除已设置的服务站
                        mtCustomEquipService.updateById(mtCustomEquip);
                    }
                }
            }
        }
        mtCustormService.updateById(mtCustorm);
        return Result.OK("服务站设置成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "客户表-通过id删除")
    @ApiOperation(value = "客户表-通过id删除", notes = "客户表-通过id删除")
    @DeleteMapping(value = "/delete")
    @RequiresPermissions("custom:delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        mtCustormService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "客户表-批量删除")
    @ApiOperation(value = "客户表-批量删除", notes = "客户表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    @RequiresPermissions("custom:deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mtCustormService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 批量设置服务商
     *
     * @param map
     * @return
     */
    @AutoLog(value = "客户表-批量设置服务商")
    @ApiOperation(value = "客户表-批量设置服务商", notes = "客户表-批量设置服务商")
    @RequestMapping(value = "/allotBatch", method = {RequestMethod.PUT, RequestMethod.POST})
    @RequiresPermissions("custom:allotBatch")
    public Result<String> allotBatch(@RequestBody Map<String, String> map) {
        String ids = map.get("ids");
        String providerId = map.get("providerId");
        this.mtCustormService.allotBatchMain(Arrays.asList(ids.split(",")), providerId);
        return Result.OK("批量设置服务商成功!");
    }

    /**
     * 批量设置服务站
     *
     * @param map
     * @return
     */
    @AutoLog(value = "客户表-批量设置服务站")
    @ApiOperation(value = "客户表-批量设置服务站", notes = "客户表-批量设置服务站")
    @RequestMapping(value = "/allotStationBatch", method = {RequestMethod.PUT, RequestMethod.POST})
    @RequiresPermissions("custom:allotStationBatch")
    public Result<String> allotStationBatch(@RequestBody Map<String, String> map) {
        String ids = map.get("ids");
        String stationId = map.get("stationId");
        this.mtCustormService.allotStationBatchMain(Arrays.asList(ids.split(",")), stationId);
        return Result.OK("批量设置服务站成功!");
    }


    /**
     * 查询客户信息
     *
     * @return
     */
    @ApiOperation(value = "客户表-查询客户信息", notes = "客户表-查询客户信息")
    @GetMapping(value = "/queryInfo")
    public Result queryInfo() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        if (sysUser.getUserType() != 4) {
            return Result.OK();
        }
        MtCustorm custorm = mtCustormService.getOne(new LambdaQueryWrapper<MtCustorm>()
                .eq(MtCustorm::getUserId, loginUser.getUsername()));
        return Result.OK(custorm);
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportXls")
    @RequiresPermissions("custom:export")
    public ModelAndView exportXls(HttpServletRequest request, MtCustorm mtCustorm) {
        return super.exportXls(request, mtCustorm, MtCustorm.class, "客户表");
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @RequiresPermissions("custom:import")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MtCustorm.class);
    }
    /*---------------------------------主表处理-end-------------------------------------*/


    /*--------------------------------子表处理-客户设备表-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    //@AutoLog(value = "客户设备表-通过主表ID查询")
    @ApiOperation(value = "客户设备表-通过主表ID查询", notes = "客户设备表-通过主表ID查询")
    @GetMapping(value = "/listMtCustomEquipByMainId")
    public Result<IPage<MtCustomEquip>> listMtCustomEquipByMainId(MtCustomEquip mtCustomEquip,
                                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                  HttpServletRequest req) {
        QueryWrapper<MtCustomEquip> queryWrapper = QueryGenerator.initQueryWrapper(mtCustomEquip, req.getParameterMap());
        Page<MtCustomEquip> page = new Page<MtCustomEquip>(pageNo, pageSize);
        IPage<MtCustomEquip> pageList = mtCustomEquipService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    /**
     * 通过客户ID查询客户设备（无分页）
     *
     * @return
     */
    @ApiOperation(value = "客户设备表-通过客户ID查询客户设备（无分页）", notes = "客户设备表-通过客户ID查询客户设备（无分页）")
    @GetMapping(value = "/listCustomEquipByCustomId")
    public Result<List<MtCustomEquip>> listMtCustomEquipByMainId(@RequestParam(name = "id", required = true) String id) {
        List<MtCustomEquip> mtCustomEquips = mtCustomEquipService.list(new LambdaQueryWrapper<MtCustomEquip>()
                .eq(MtCustomEquip::getCustomId, id));
        return Result.OK(mtCustomEquips);
    }

    /**
     * 根据当前登录用户获取客户设备列表
     *
     * @return
     */
    //@AutoLog(value = "客户设备表-通过主表ID查询")
    @ApiOperation(value = "客户设备表-根据当前登录用户获取客户设备列表", notes = "客户设备表-根据当前登录用户获取客户设备列表")
    @GetMapping(value = "/listMtCustomEquipByLoginUser")
    public Result<IPage<MtCustomEquip>> listMtCustomEquipByLoginUser(MtCustomEquip mtCustomEquip,
                                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                     HttpServletRequest req) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();//2.0版本获取当前登录用户
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        QueryWrapper<MtCustomEquip> queryWrapper = QueryGenerator.initQueryWrapper(mtCustomEquip, req.getParameterMap());
        // 用户为服务商,根据账号获取服务商
        if (sysUser.getUserType() == 1) {
            MtServiceProviders providers = mtServiceProvidersService.getOne(new LambdaQueryWrapper<MtServiceProviders>()
                    .eq(MtServiceProviders::getUserId, loginUser.getUsername()));
            if (Objects.isNull(providers)) {
                return Result.error("无该服务商信息");
            }
            queryWrapper.lambda().eq(MtCustomEquip::getProviderId, providers.getId());
        }
        // 用户为工作站,根据账号获取工作站
        else if (sysUser.getUserType() == 2) {
            MtServiceStation station = mtServiceStationService.getOne(new LambdaQueryWrapper<MtServiceStation>()
                    .eq(MtServiceStation::getUserId, loginUser.getUsername()));
            if (Objects.isNull(station)) {
                return Result.error("无该工作站信息");
            }
            queryWrapper.lambda().eq(MtCustomEquip::getStationId, station.getId());
        }
        // 用户为客户,根据账号获取客户
        else if (sysUser.getUserType() == 4) {
            MtCustorm custorm = mtCustormService.getOne(new LambdaQueryWrapper<MtCustorm>()
                    .eq(MtCustorm::getUserId, loginUser.getUsername()));
            if (Objects.isNull(custorm)) {
                return Result.error("无该客户信息");
            }
            queryWrapper.lambda().eq(MtCustomEquip::getCustomId, custorm.getId());
        }
        // 其他
        else {
            return Result.error("该登录用户无权查看客户设备");
        }
        Page<MtCustomEquip> page = new Page<MtCustomEquip>(pageNo, pageSize);
        IPage<MtCustomEquip> pageList = mtCustomEquipService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param mtCustomEquip
     * @return
     */
    @AutoLog(value = "客户设备表-添加")
    @ApiOperation(value = "客户设备表-添加", notes = "客户设备表-添加")
    @PostMapping(value = "/addMtCustomEquip")
    public Result<String> addMtCustomEquip(@RequestBody MtCustomEquip mtCustomEquip) {
        mtCustomEquipService.save(mtCustomEquip);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mtCustomEquip
     * @return
     */
    @AutoLog(value = "客户设备表-编辑")
    @ApiOperation(value = "客户设备表-编辑", notes = "客户设备表-编辑")
    @RequestMapping(value = "/editMtCustomEquip", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> editMtCustomEquip(@RequestBody MtCustomEquip mtCustomEquip) {
        mtCustomEquipService.updateById(mtCustomEquip);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "客户设备表-通过id删除")
    @ApiOperation(value = "客户设备表-通过id删除", notes = "客户设备表-通过id删除")
    @DeleteMapping(value = "/deleteMtCustomEquip")
    public Result<String> deleteMtCustomEquip(@RequestParam(name = "id", required = true) String id) {
        mtCustomEquipService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "客户设备表-批量删除")
    @ApiOperation(value = "客户设备表-批量删除", notes = "客户设备表-批量删除")
    @DeleteMapping(value = "/deleteBatchMtCustomEquip")
    public Result<String> deleteBatchMtCustomEquip(@RequestParam(name = "ids", required = true) String ids) {
        this.mtCustomEquipService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportMtCustomEquip")
    public ModelAndView exportMtCustomEquip(HttpServletRequest request, MtCustomEquip mtCustomEquip) {
        // Step.1 组装查询条件
        QueryWrapper<MtCustomEquip> queryWrapper = QueryGenerator.initQueryWrapper(mtCustomEquip, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<MtCustomEquip> pageList = mtCustomEquipService.list(queryWrapper);
        List<MtCustomEquip> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, "客户设备表");
        mv.addObject(NormalExcelConstants.CLASS, MtCustomEquip.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("客户设备表报表", "导出人:" + sysUser.getRealname(), "客户设备表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importMtCustomEquip/{mainId}")
    public Result<?> importMtCustomEquip(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MtCustomEquip> list = ExcelImportUtil.importExcel(file.getInputStream(), MtCustomEquip.class, params);
                for (MtCustomEquip temp : list) {
                    temp.setCustomId(mainId);
                }
                long start = System.currentTimeMillis();
                mtCustomEquipService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.OK("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-客户设备表-end----------------------------------------------*/


}
